// src/store/userStore.ts
import { defineStore } from "pinia";
import { getUserDetail, type UserDetailInfoData } from "@/api/Member";

export const useUserStore = defineStore("user", {
  state: () => ({
    userDetail: null as UserDetailInfoData | null,
    loading: false,
    error: null as Error | null
  }),

  actions: {
    async fetchUserDetail() {
      this.loading = true;
      this.error = null;
      try {
        const res = await getUserDetail();
        this.userDetail = res;
        return res;
      } catch (err) {
        this.error = err as Error;
        throw err;
      } finally {
        this.loading = false;
      }
    },

    // 更新用户信息（部分更新）
    updateUserDetail(payload: Partial<UserDetailInfoData>) {
      if (this.userDetail) {
        this.userDetail = { ...this.userDetail, ...payload };
      }
    }
  },

  getters: {
    // 获取AI币余额
    aiCoinBalance: state => state.userDetail?.assetDetail?.aiCoinBalance || 0,
    // 获取数字人数量
    humanAmount: state => state.userDetail?.userMakeAssetVo?.humanAmount || 0,
    // 获取头像URL
    avatarUrl: state => (defaultUrl: string) =>
      state.userDetail?.headimgurl || defaultUrl,
    // 获取昵称
    nickname: state => state.userDetail?.nickname || "",
    // 获取用户ID
    userId: state => state.userDetail?.userId || "",
    // 获取手机号
    mobile: state => state.userDetail?.mobile || ""
  }
});
